import { api } from "@/utils/api";
import { useStore } from "@/store";
const store = useStore();

//获取用户信息
const getInfo = () => {
    return new Promise(async (resolve, reject) => {
        const config = {
            path: '/getInfo',
            method: "GET",
        }
        const res = await api(config);
        const { code } = res;
        if(code>209) reject(res);
        resolve(res)
    })
}

//获取图片验证码
export const getCaptcha = () => {
    return new Promise(async (resolve, reject) => {
        const config = { path: '/captchaImage', title: '连接服务器中...' }
        const res = await api(config)
        if(res.code > 209){
            uni.showModal({
                title: '验证码获取失败',
                content: res['msg'],
            })
            reject(res['msg'])
        }
        resolve({ Captcha : `data:image/png;base64,${res['img']}`, uuid: res['uuid'] })
    })

}

//登录接口
export const login = userForm => {
    return new Promise(async (resolve, reject) => {
        const path = '/login'
        const method = 'POST'
        const body = userForm
        const config = {path, method, body}
        try {
            const res = await api(config);
            if (res.code>209) reject(res.msg)
            await store.setToken(res.token);
            try{
                const userInfo = await getInfo()
                store.setUserInfo(userInfo.user)
                resolve(userInfo)
            }catch(err){
                reject(err)
            }
        }catch (err){
            uni.showModal({
                title: '登录失败',
                content: err+"\n 请点击验证码或输入正确的账号密码"
            })
            reject(err)
        }
    })
}

//获取所有商品
export const getShopList = (pageNum, pageSize, classid= 5)=> {
    return new Promise(async (resolve, reject) =>{
        const res = await api({url: '/My/My/class', params: { pageNum, pageSize, classid }})
        if(res?.code>209)reject(res.message)
        resolve(res)
    })
}
